import { Message, Notification } from "element-ui";

/**
 * 获取年月日
 * @param {(Object|string|number)} time
 * @param {string} cFormat
 * @returns {string | null}
 */
export function parseTime(time, cFormat) {
  if (arguments.length === 0) {
    return null;
  }
  const format = cFormat || "{y}-{m}-{d} {h}:{i}:{s}";
  let date;
  if (typeof time === "object") {
    date = time;
  } else {
    if (typeof time === "string" && /^[0-9]+$/.test(time)) {
      time = parseInt(time);
    }
    if (typeof time === "number" && time.toString().length === 10) {
      time = time * 1000;
    }
    date = new Date(time);
  }
  const formatObj = {
    y: date.getFullYear(),
    m: date.getMonth() + 1,
    d: date.getDate(),
    h: date.getHours(),
    i: date.getMinutes(),
    s: date.getSeconds(),
    a: date.getDay()
  };
  const time_str = format.replace(/{([ymdhisa])+}/g, (result, key) => {
    const value = formatObj[key];
    // Note: getDay() returns 0 on Sunday
    if (key === "a") {
      return ["日", "一", "二", "三", "四", "五", "六"][value];
    }
    return value.toString().padStart(2, "0");
  });
  return time_str;
}

/**
 * 获取明天的年月日
 */
export function getDefaultDate() {
  const date = new Date();
  date.setDate(date.getDate() + 1);
  const year = date.getFullYear();
  const month = String(date.getMonth() + 1).padStart(2, "0");
  const day = String(date.getDate()).padStart(2, "0");
  const formattedDate = `${year}-${month}-${day}`;
  return formattedDate;
}

/**
 * 获取具体时间
 * @param {number} time
 * @param {string} option
 * @returns {string}
 */
export function formatTime(time, option) {
  if (("" + time).length === 10) {
    time = parseInt(time) * 1000;
  } else {
    time = +time;
  }
  const d = new Date(time);
  const now = Date.now();

  const diff = (now - d) / 1000;

  if (diff < 30) {
    return "刚刚";
  } else if (diff < 3600) {
    // less 1 hour
    return Math.ceil(diff / 60) + "分钟前";
  } else if (diff < 3600 * 24) {
    return Math.ceil(diff / 3600) + "小时前";
  } else if (diff < 3600 * 24 * 2) {
    return "1天前";
  }
  if (option) {
    return parseTime(time, option);
  } else {
    return (
      d.getMonth() +
      1 +
      "月" +
      d.getDate() +
      "日" +
      d.getHours() +
      "时" +
      d.getMinutes() +
      "分"
    );
  }
}

/**
 * 获取本月开始时间和结束时间
 */
export function getWeekStartAndEnd() {
  var firstDate = new Date();
  var startDate =
    firstDate.getFullYear() +
    "-" +
    (firstDate.getMonth() + 1 < 10 ? "0" : "") +
    (firstDate.getMonth() + 1) +
    "-" +
    "01";
  var date = new Date();
  var currentMonth = date.getMonth();
  var nextMonth = ++currentMonth;
  var nextMonthFirstDay = new Date(date.getFullYear(), nextMonth, 1);
  var oneDay = 1000 * 60 * 60 * 24;
  var lastDate = new Date(nextMonthFirstDay - oneDay);
  var endDate =
    lastDate.getFullYear() +
    "-" +
    (lastDate.getMonth() + 1 < 10 ? "0" : "") +
    (lastDate.getMonth() + 1) +
    "-" +
    (lastDate.getDate() < 10 ? "0" : "") +
    lastDate.getDate();
  return [startDate, endDate];
}

// 获取前五天的时间  零点到24点
export function getFiveday() {
  const time = new Date().getTime() - 24 * 60 * 60 * 1000 * 4;
  const nowtime = new Date().getTime();
  var Fiveday = parseTime(time, "{y}-{m}-{d}");
  var now = parseTime(nowtime, "{y}-{m}-{d}");
  var start = Fiveday + " " + "00:00:00";
  var end = now + " " + "23:59:59";
  return [start, end];
}
// 获取昨天的时间  零点到24点
export function getyesterday() {
  const time = new Date().getTime() - 24 * 60 * 60 * 1000;
  var yesterday = parseTime(time, "{y}-{m}-{d}");
  var start = yesterday + " " + "00:00:00";
  var end = yesterday + " " + "23:59:59";
  return [start, end];
}
// 获取明天的时间  零点到24点
export function gettomorrow() {
  const time = new Date().getTime() + 24 * 60 * 60 * 1000;
  var yesterday = parseTime(time, "{y}-{m}-{d}");
  var start = yesterday + " " + "00:00:00";
  var end = yesterday + " " + "23:59:59";
  return [start, end];
}
//获取上月初到月底
export function getLastMonthAndDay() {
  var nowDate = new Date();
  var year = nowDate.getFullYear();
  var month = nowDate.getMonth();
  if (month == 0) {
    month = 12;
    year = year - 1;
  }
  var lastDay = new Date(year, month, 0);
  var start = year + "-" + month + "-" + lastDay.getDate();
  var end = year + "-" + month + "-" + "01";
  return [start, end];
}

// 获取上周周一到周日
export function getLastWeekAndDay() {
  var date = new Date();
  var dateTime = date.getTime(); // 获取现在的时间
  var dateDay = date.getDay();
  var oneDayTime = 24 * 60 * 60 * 1000;
  var proWeekList = [];
  proWeekList[0] = dateTime - (dateDay + (7 - 1 - 0)) * oneDayTime;
  proWeekList[1] = dateTime - (dateDay + (7 - 1 - 6)) * oneDayTime;

  return proWeekList;
}
// 获取当前星期几
export function getWeekDate() {
  var now = new Date();
  var day = now.getDay();
  var weeks = new Array(
    "星期日",
    "星期一",
    "星期二",
    "星期三",
    "星期四",
    "星期五",
    "星期六"
  );
  var week = weeks[day];
  return week;
}
// 获取当月时间
export function getNowMonth() {
  var date = new Date(),
    y = date.getFullYear(),
    m = date.getMonth();
  var firstDay = new Date(y, m, 1);
  var lastDay = new Date(y, m + 1, 0);
  firstDay = parseTime(firstDay, "{y}-{m}-{d}");
  lastDay = parseTime(lastDay, "{y}-{m}-{d}");
  return [firstDay, lastDay];
}
/**
 * 获取网址参数
 * @param {string} url
 * @returns {Object}
 */
export function param2Obj(url) {
  const search = url.split("?")[1];
  if (!search) {
    return {};
  }
  return JSON.parse(
    '{"' +
    decodeURIComponent(search)
      .replace(/"/g, '\\"')
      .replace(/&/g, '","')
      .replace(/=/g, '":"')
      .replace(/\+/g, " ") +
    '"}'
  );
}

/**
 * 分类递归
 */
export function recursion(data, type) {
  if (type) {
    data = [{ company_id: 0, id: 0, selfNext: [], title: "所有" }].concat(data);
  }
  data.map(e => {
    if (e.selfNext.length != 0) {
      categoryNext(e.selfNext);
    } else {
      e.selfNext = undefined;
    }
  });
  function categoryNext(arry) {
    arry.map(e => {
      if (e.selfNext.length != 0) {
        this.categoryNext(e.selfNext);
      } else {
        e.selfNext = undefined;
      }
    });
  }
  return data;
}

/**
 * 子分类判断
 */
export function category(data) {
  return data ? (data.length > 1 ? data[data.length - 1] : "") : "";
}

/**
 * 查找分类中的项
 */
export function findCategory(id,data) {
  for (const item of data) {
    if (item.id === id) {
      return item;
    }
    if (item.selfNext) {
      const foundItem = findCategory(id, item.selfNext);
      if (foundItem) {
        return foundItem;
      }
    }
  }
}

/* 
  导出封装
  res，后端请求来的文件流
  name，导出的文件名
*/
export function exportMethod(res, name, notify) {
  let fileReader = new FileReader();
  fileReader.readAsText(res, "utf-8");
  fileReader.onload = function () {
    try {
      let jsonData = JSON.parse(this.result);  // 说明是普通对象数据，后台转换失败+
      if (jsonData.errcode) {
        notify.close();
        Notification.error({
          title: jsonData.errmsg,
          duration: 3000,
        })
      } else if (jsonData.code) {
        notify.close();
        Notification.error({
          title: jsonData.msg,
          duration: 3000,
        })
      }
    } catch (err) {
      notify.close();
      Notification.success({
        title: '导出成功',
        duration: 3000,
      })
      const link = document.createElement("a");
      let blob = new Blob([res], {
        type:
          "application/vnd.ms-excel,application/vnd.openxmlformats-officedocument.spreadsheetml.sheet"
      });
      link.style.display = "none";
      link.href = URL.createObjectURL(blob);
      link.download = name;
      document.body.appendChild(link);
      link.click();
      document.body.removeChild(link);
    }
  };
}


export function fileDownLoad(res, name) {
  let fileReader = new FileReader();
  fileReader.readAsDataURL(res);
  fileReader.onload = (event) => {
    let a = document.createElement('a');
    a.download = name;
    a.href = event.target.result;
    document.body.appendChild(a);
    a.click();
    document.body.removeChild(a);
  }
}

export function urlDownload(url){
  let a = document.createElement('a');
    a.href = url;
    document.body.appendChild(a);
    a.click();
    document.body.removeChild(a);
}
/* 
  JSON.stringify  被转换值中有 undefined、任意的函数以及 symbol 值
*/
export function jsonStringifyBack(key, value) {
  if (value === undefined) {
    return "";
  } else if (typeof value === "symbol" || typeof value === "function") {
    return value.toString();
  }
  return value;
}

/* 一键复制到剪贴板 */
export function copyToClipboard(content) {
  if (window.clipboardData) {
    window.clipboardData.setData("text", content);
  } else {
    (function (content) {
      document.oncopy = function (e) {
        e.clipboardData.setData("text", content);
        e.preventDefault();
        document.oncopy = null;
      };
    })(content);
    document.execCommand("Copy");
  }
}

// 判断输入的值是否是数字或小数点
function isNumber(value){
  if (value.includes("-")) {
    Message.error("不能输入负数");
  }
  const regex = /^-?\d+(\.\d{0,2})?$/; // 允许输入负数，最多二位小数
  if (!regex.test(value)) {
    // 如果不符合要求，则从输入中移除非法字符
    value = value.replace(/[^0-9.]/g, ""); // 移除非数字和非小数点的字符
    const parts = value.split("."); // 按小数点分割字符串
    if (parts.length > 2) {
      // 如果小数点超过一个
      value = parts[0] + "." + parts.slice(1).join(""); // 只保留第一个小数点，后面的小数点删除
    } else if (parts.length === 2) {
      // 如果有小数部分
      parts[1] = parts[1].slice(0, 2); // 保留小数部分的前两位数字
      value = parts.join(".");
    }
    return value;
  } else {
    return value;
  }
}

export function handleNumInput(row,key){
  let value = row[key]
  row[key] = isNumber(value);
}